package com.promise.jokerdream.work.signin.newact

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 刮刮卡工作
    class ScratchCardWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "刮刮卡"

    override val priority: Int
        get() = 8

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        return try {
            queryScratchCardInfo()
        } catch (e: Exception) {
            WorkResult.Failure(e, "刮刮卡工作执行异常: ${e.message}")
        }
    }

    /**
     * 查询刮刮卡信息并执行刮卡操作
     */
    private suspend fun queryScratchCardInfo(): WorkResult {
        // 先查询刮刮卡信息
        val queryResult = gameApi.queryScratchCard()
        
        return queryResult.fold(
            onSuccess = { response ->
                // 先领取任务奖励
                claimTaskRewards(response.task)
                
                // 领取奖励后重新查询刮刮卡信息，获取最新的cardNum
                val updatedQueryResult = gameApi.queryScratchCard()
                updatedQueryResult.fold(
                    onSuccess = { updatedResponse ->
                        if (updatedResponse.cardNum > 0) {
                            executeScratchCards(updatedResponse.cardNum)
                        } else {
                            WorkResult.Success
                        }
                    },
                    onFailure = { exception ->
                        if (response.cardNum > 0) {
                            executeScratchCards(response.cardNum)
                        } else {
                            WorkResult.Success
                        }
                    }
                )
            },
            onFailure = { exception ->
                WorkResult.Failure(exception, exception.message)
            }
        )
    }
    
    /**
     * 领取任务奖励
     * @param tasks 任务列表
     */
    private suspend fun claimTaskRewards(tasks: List<com.promise.jokerdream.model.ScratchCardTaskModel>) {
        tasks.forEach { task ->
            // 检查任务状态：1为已完成但未领取，需要领取奖励
            if (task.state == 1) {
                val claimResult = gameApi.rewardScratchCard(task.id)
                claimResult.fold(
                    onSuccess = { response ->
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(name, exception.message)
                    }
                )
                
                // 添加延迟避免请求过于频繁
                kotlinx.coroutines.delay(300)
            }
        }
    }
    
    /**
     * 执行刮卡操作
     * @param cardCount 刮卡次数
     */
    private suspend fun executeScratchCards(cardCount: Int): WorkResult {
        repeat(cardCount) { index ->
            val scratchResult = gameApi.scratchCard()
            scratchResult.fold(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, "${exception.message}")
                }
            )
            
            // 添加延迟避免请求过于频繁
            if (index < cardCount - 1) {
                kotlinx.coroutines.delay(500) // 延迟500ms
            }
        }
        
        return WorkResult.Success
    }
}